require "Player"
require "HUD"

LocalPlayer = Player:new{
	locationTimer = 0.0,
	msgProcess = nil,
	hud = nil,
}

function LocalPlayer:create(playerFile, world, player)
	return player or Player.create(self, playerFile, world, LocalPlayer:new())
end

function LocalPlayer:onEnter()
	Misc:log("LocalPlayer : onEnter .. " .. Misc:getNodeName(self))
	
	--call super func
	Player.onEnter(self)
	
    self.msgProcess = CPlayerMsgProcess:getInstancePtr()
    
	local function syncLocation(dt)
        self:syncLocation(dt)
    end
	self.updateID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(syncLocation, 0.5, false)
	
	self.hud = HUD:create(self.world)
end

function LocalPlayer:syncLocation(dt)
	if bMoving then 
		self.msgProcess:writeUint16(Protocol.NET_PLAYER_LOCATION)
		self.msgProcess:writeInt32(self.localPlayerID)
		self.msgProcess:writeFloat(self:getPositionLua().x)
		self.msgProcess:writeFloat(self:getPositionLua().y)
		self.msgProcess:sendMsg(Protocol.NET_PLAYER_LOCATION)
	end
end

function LocalPlayer:setLife(life)
	self.hud:setLife(life)
	Player.setLife(self, life)
end

function LocalPlayer:onExit()
	--call super func
	Player.onExit(self)
end

function LocalPlayer:move(delta)
	local curLocation = self:getPositionLua()
	local newLocation = ccpAdd(curLocation, delta)
	local mapLocation = ccpSub(self.world.map:getPositionLua(), delta)
	
	local block = self.world.map:blockAt(newLocation)
	if block == 1 then
	elseif block == 2 then
		self:setOpacity(128)
		self.world.map:setPosition(mapLocation.x, mapLocation.y)
		self:setPosition(newLocation.x, newLocation.y) 
	else
		self:setOpacity(255)
		self.world.map:setPosition(mapLocation.x, mapLocation.y)
		self:setPosition(newLocation.x, newLocation.y) 
	end
end

function LocalPlayer:tick(dt)
	--call super func
	Player.tick(self, dt)
	
	CNetManager:getInstancePtr():tick()
end